/**
 * Copyright 2008 Vidar Svansson
 *
 * This file is part of JAdapter.
 *
 * JAdapter is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JAdapter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JAdapter.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.jadapter.spring.config;

import org.jadapter.JAdapter;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.beans.factory.parsing.Location;
import org.springframework.beans.factory.parsing.Problem;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

/**
 *
 * @author Vidar Svansson
 * @since 0.3
 */
public class AdapterDefinitionParser extends AbstractSingleBeanDefinitionParser {

    protected Class getBeanClass(Element element) {
        return JAdapter.class;
    }


    protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder bean) {

        String pattern = element.getAttribute("class");

        try {
            Class factory = Class.forName(pattern);
            bean.addConstructorArgValue(factory);

        } catch (ClassNotFoundException e) {

            throw new BeanDefinitionParsingException(
                    new Problem("adapter class not found " + pattern,
                        new Location(parserContext.getReaderContext().getResource()))
            );

        }

        String to = element.getAttribute("to");
        if (StringUtils.hasText(to)) {
            bean.addPropertyValue("to", Boolean.valueOf(to));
        }
        String from = element.getAttribute("from");
        if (StringUtils.hasText(to)) {
            bean.addPropertyValue("from", Boolean.valueOf(from));
        }


    }
}
